--
-- Author: shunguo.chen
-- Date: 2018-03-16 10:36:05
--
-- ChessMiniPanel 谜棋小地图

local ChessMiniRender = import(".renders.ChessMiniRender")
local ChessHeadRender = import(".renders.ChessHeadRender")
local ChessMiniTipRender = import(".renders.ChessMiniTipRender")

local ActionManager = cc.Director:getInstance():getActionManager()

local ClassRef = app.mvc.createPanelClass(...)

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.ChessMiniPanel))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	-- 最大格子数
	local cellMax = Constant.CHESS_MAX_CELL

	local _, height = self._ui.Panel_mini:getContentSize2()
	self._ui.Panel_mini:setContentSize(cc.size(display.safe_width, height))
	ccui.Helper:doLayout(self._ui.Panel_mini)

	self._ui.Button_1:addClickEventListener(function()
			self:_adjustPanel(1, 1)
		end)
	self._ui.Button_2:addClickEventListener(function()
			self:_adjustPanel(cellMax, 1)
		end)

	local action = cca.repeatForever(cca.seq({cca.moveBy(0.6, -10, 0), cca.moveBy(0.3, 10, 0)}))
	self._ui.Button_1:runAction(action)
	action = cca.repeatForever(cca.seq({cca.moveBy(0.6, 10, 0), cca.moveBy(0.3, -10, 0)}))
	self._ui.Button_2:runAction(action)

	-- tip
	local tip = ChessMiniTipRender.create()
	tip:setVisible(false)
	self:addChild(tip, 2)

	-- mini map
	local map = cc.CSLoader:createNode(Res["ChessMiniMapNode_" .. cellMax])
	local panel = map:getChildByName("Panel")
	panel:removeFromParent(false)
	self._myHead = ChessHeadRender.create(panel:getChildByName("player_1"))
	self._myHead:setLocalZOrder(2)
	self._enemyHead = ChessHeadRender.create(panel:getChildByName("player_2"))
	self._enemyHead:setLocalZOrder(3)

	local renders = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
	self._renders = renders
	for i=1,cellMax do
		local node = panel:getChildByName("map_" .. i)
		local render = ChessMiniRender.create()
		render:setIndex(i)
		renders[i] = render
		render:setPosition(node:getPosition())
		render:setTouchTip(tip)
		panel:addChild(render)
		node:removeFromParent()
	end

	local Node_isVisible = cc.Node.isVisible
	local Tip_hide = ChessMiniTipRender.hide
	local function scrollViewEvent(sender, eventType)
		if eventType == ccui.ScrollviewEventType.scrolling then
			if Node_isVisible(tip) then
				Tip_hide(tip)
			end
		end
	end

	local sv = self._ui.ScrollView
	sv:addEventListener(scrollViewEvent)
	sv:addChild(panel)
	panel:setPosition(0, 0)

	local size = panel:getContentSize()
	sv:setInnerContainerSize(size)

	-- sv的宽／内部容器宽
	local svWidth = sv:getContentSize2()
	self._svInnerWidth = size.width
	self._svHalfWidth = svWidth / 2
	self._svXMax = self._svInnerWidth - svWidth
	self._sv = sv

	-- 是否移动中，移动中缓存移动数据，等移动完再执行下一次移动
	self._isInMyMove = false
	self._isInEnemyMove = false
	self._myMoveDatas = {}
	self._enemyMoveDatas = {}
end

function ClassRef:show()
	self:setVisible(true)

	ActionManager:resumeTarget(self._ui.Button_1)
	ActionManager:resumeTarget(self._ui.Button_2)
end

function ClassRef:hide()
	self:setVisible(false)

	ActionManager:pauseTarget(self._ui.Button_1)
	ActionManager:pauseTarget(self._ui.Button_2)

	self._myHead:stopAllActions()
	self._enemyHead:stopAllActions()
	self._isInMyMove = false
	self._isInEnemyMove = false
	self._myMoveDatas = {}
	self._enemyMoveDatas = {}

	for i,render in ipairs(self._renders) do
		render:setLight(false, true)
		render:setLight(false, false)
	end
end

function ClassRef:refresh()
	local info = self._data
	self._myHead:setData(info.myPlayer)
	self._enemyHead:setData(info.enemyPlayer)

	local cells = info.cells
	for i,render in ipairs(self._renders) do
		render:setData(cells[i])
	end

	self:roundChange()
end

function ClassRef:_adjustPanel(pos, time)
	-- 按pos位置居中
	-- calculate current percent
	local innerPosX = self._sv:getInnerContainer():getPositionX()
	local curPer = math.abs(innerPosX) / self._svXMax

	-- print("innerPosX, curPer", innerPosX, curPer)

	-- calculate next percent
	local render = self._renders[pos]
	local posX = render:getPositionX()
	local dis = posX - self._svHalfWidth
	dis = math.max(dis, 0)
	dis = math.min(dis, self._svXMax)
	local nextPer = dis / self._svXMax

	-- print("posX, dis, nextPer", posX, dis, nextPer)

	if nextPer ~= curPer then
		self._sv:scrollToPercentHorizontal(nextPer * 100, time, false)
	end
end

function ClassRef:_moveToRrender(curPos, tarPos, isMe)
	-- print("ChessMiniPanel moveToRrender start", curPos, tarPos)
	if isMe and self._isInMyMove then 
		-- 是我自己
		local data = {curPos=curPos, tarPos=tarPos, isMe=isMe}
		self._myMoveDatas[#self._myMoveDatas + 1] = data
		return
	elseif not isMe and self._isInEnemyMove then
		local data = {curPos=curPos, tarPos=tarPos, isMe=isMe}
		self._enemyMoveDatas[#self._enemyMoveDatas + 1] = data
		return
	end

	if isMe then
		self._isInMyMove = true
	else
		self._isInEnemyMove = true
	end

	local factor = (curPos < tarPos) and 1 or -1
	for i=curPos+factor,tarPos,factor do
		self._renders[i]:setLight(true, isMe)
	end

	local nextPos = curPos
	local curHead = isMe and self._myHead or self._enemyHead

	local function moveToNextPos()
		nextPos = nextPos + factor
		-- print("moveToNextPos", nextPos)
		if (factor == 1 and nextPos <= tarPos) or (factor == -1 and nextPos >= tarPos) then
			local nextRender = self._renders[nextPos]
			local curX = self._renders[nextPos-factor]:getPositionX()
			local x, y = nextRender:getPosition()
			local move = cca.moveTo(0.4, x, y)
			local func = cca.cb(function()
					nextRender:setLight(false, isMe)
					moveToNextPos()
				end)
			curHead:runAction(cca.seq({move, func}))

			if curX ~= x then
				-- 有x方向移动
				self:_adjustPanel(nextPos, 0.4)
			end
		else
			-- print("ChessMiniPanel moveToRrender end")
			self._renders[tarPos]:refresh()
			if isMe then
				self._isInMyMove = false
				if #self._myMoveDatas > 0 then
					local data = table.remove(self._myMoveDatas, 1)
					self:_moveToRrender(data.curPos, data.tarPos, data.isMe)
				end
			else
				self._isInEnemyMove = false
				if #self._enemyMoveDatas > 0 then
					local data = table.remove(self._enemyMoveDatas, 1)
					self:_moveToRrender(data.curPos, data.tarPos, data.isMe)
				end
			end
		end
	end

	moveToNextPos()
end

function ClassRef:roundChange()
	local info = self._data
	local myPlayer = info.myPlayer
	local enemyPlayer = info.enemyPlayer

	local adjustPos
	if info:isMyRound() then
		self._myHead:setLocalZOrder(3)
		self._enemyHead:setLocalZOrder(2)
		self._curHead = self._myHead
		adjustPos = myPlayer.pos
	else
		self._myHead:setLocalZOrder(2)
		self._enemyHead:setLocalZOrder(3)
		self._curHead = self._enemyHead
		adjustPos = enemyPlayer.pos
	end
	self._myHead:setPosition(self._renders[myPlayer.pos]:getPosition())
	self._enemyHead:setPosition(self._renders[enemyPlayer.pos]:getPosition())

	self:_adjustPanel(adjustPos, 1)
end

function ClassRef:playerMove(startPos)
	local curActionPlayer = self._data:getCurActionPlayer()
	local tarPos = curActionPlayer.pos
	local isMyAction = self._data:isMyAction()
	if isMyAction then
		self._myHead:setLocalZOrder(3)
		self._enemyHead:setLocalZOrder(2)
	else
		self._myHead:setLocalZOrder(2)
		self._enemyHead:setLocalZOrder(3)
	end

	self:_moveToRrender(startPos, tarPos, isMyAction)
end

return ClassRef